const Koa=require('koa')
const app=new Koa()
const router=require('koa-router')()
const bodyparser=require('koa-bodyparser')
const query=require('./db/index')



//添加发票
//duty:税号
router.post('/addlist',async ctx=>{
    let {type,name,duty='',email,fapiao=0,isdefault}=ctx.request.body;

    if(!type||!name||!email||!isdefault){
        ctx.body={
            code:2,
            msg:"缺少参数"
        }
        return;
    }

    //判断默认发票
    if(isdefault==1){
        let user=await query(`select * from fapiao where isdefault=1`)
        ctx.body={
            user
        }

        if(user.length==1){
            let listupdata=await query(`updata fapiao set isdefault=0 where id=${user[0].id}`)
        }
    }


    //添加数据
    //insert inito 表名 (表里的变量) values ()
    let res=await query(`insert into fapiao (type,name,duty,email,fapiao,isdefault) values (${type},'${name}','${duty}','${email}',${fapiao},${isdefault})`)

    ctx.body=res
})



//获取发票
router.get('/listfapiao',async ctx=>{
    let res=await query(`select * from fapiao`)
    ctx.body={
        code:0,
        data:res,
        msg:'连接成功'
    }
})



router.get('/list',async ctx=>{
    ctx.body={
        code:0,
        msg:'1111'
    }
})


app.use(bodyparser())
app.use(router.routes(),router.allowedMethods())


app.listen(3000)